package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.DaoBlog;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DaoBlog daoBlog = new DaoBlog();
        List<Blog> blogs = null;
        String blogId = req.getParameter("blogId");
        String respJson = "";
        if(blogId == null){
            //为空说明返回列表页
            //查询数据库,查询之后构造出要求的数据格式并返回
            //建立连接
            //构建sql语句
            //获取博客列表
            //返回博客列表
            blogs = daoBlog.getBlogs();
            respJson = objectMapper.writeValueAsString(blogs);
        }else {
            //返回详情页
           Blog blog = daoBlog.getBlogById(Integer.parseInt(blogId));
           respJson = objectMapper.writeValueAsString(blog);

        }
        resp.setContentType("application/json; charset=utf8");
        resp.setStatus(200);
        resp.getWriter().write(respJson);



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
